export default class HexUtils {

  /**
   * 将 ArrayBuffer 转换为 Hex 格式字符串
   * @param buffer - ArrayBuffer
   * @returns Hex 格式字符串
   */
  public static bufferToHex(buffer: ArrayBuffer): string {
    const bytes = new Uint8Array(buffer)
    return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
  }

  /**
   * 将 Hex 格式字符串转换为 ArrayBuffer
   * @param hex - Hex 格式字符串
   * @returns ArrayBuffer
   */
  public static hexToBuffer(hex: string): ArrayBuffer {
    const bytes = new Uint8Array(hex.length / 2)
    for (let i = 0; i < hex.length; i += 2) {
      bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16)
    }
    return bytes.buffer
  }

  /**
   * 字符串转十六进制
   * @param str
   */
  public static strToHex(str: string) {
    let hexString = ''
    for (let i = 0; i < str.length; i++) {
      const hex = str.charCodeAt(i).toString(16)
      hexString += hex.length === 1 ? '0' + hex : hex
    }
    return hexString
  }

  /**
   * 十六进制转字符串
   * @param hexStr
   */
  public static hexToStr(hexStr: string) {
    let result = ''
    for (let i = 0; i < hexStr.length; i += 2) {
      const temp = hexStr.substring(i, i + 2)
      result += String.fromCharCode(parseInt(temp, 16))
    }
    return result
  }
}
